package controller;

import model.*;

import javax.jws.soap.SOAPBinding;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2023-12-08
 * Time：21:32
 */
@WebServlet("/blogDelete")
public class BlogDeleteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.判定用户登陆状态
        HttpSession session = req.getSession(false);
        if (session==null) {
            resp.setStatus(403);
            return;
        }
        User user = (User) session.getAttribute("user");
        if (user == null) {
            resp.setStatus(403);
            return;
        }
        //2.获取blogId
        String blogId = req.getParameter("blogId");
        if (blogId == null || blogId.isEmpty()) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("要删除的文章不存在！！");
            return;
        }
        //3.删除数据库博客数据
        BlogDao blogDao = new BlogDao();
        blogDao.delete(Integer.parseInt(blogId));
        //4.更新数据库用户博客数，并且更新session值
        UserDao userDao = new UserDao();
        int newBlogCount = user.getBlogCount() - 1;
        userDao.updateBlogCount(user.getUserId(), newBlogCount);
        user.setBlogCount(newBlogCount);
        session.setAttribute("user", user);
        resp.sendRedirect("blog_list.html");

        //输出日志
        Log log = new Log();
        log.setUserId(user.getUserId());
        log.setAction("该用户删除博客成功！");
        LogDao logDao = new LogDao();
        logDao.insert(log);
    }
}
